import apiClient from './client'

// 通话类型
export type CallType = 'ONE_TO_ONE' | 'GROUP' | 'CONFERENCE'
export type MediaType = 'AUDIO' | 'VIDEO' | 'SCREEN_SHARE'
export type CallStatus = 'INITIATED' | 'RINGING' | 'CONNECTED' | 'ENDED' | 'CANCELLED' | 'REJECTED' | 'MISSED' | 'FAILED'
export type ParticipantStatus = 'INVITED' | 'RINGING' | 'JOINED' | 'LEFT' | 'REJECTED' | 'MISSED'

// 接口定义
export interface Call {
  id: string
  callType: CallType
  mediaType: MediaType
  callerId: string
  callerName?: string
  conversationId: string
  status: CallStatus
  participants: Participant[]
  startTime?: string
  endTime?: string
  duration?: number
  recordingUrl?: string
  transcriptUrl?: string
  analysisUrl?: string
  createdAt: string
}

export interface Participant {
  id: string
  userId: string
  userName?: string
  userAvatar?: string
  status: ParticipantStatus
  joinedAt?: string
  leftAt?: string
  muted: boolean
  videoEnabled: boolean
  screenSharing: boolean
}

export interface InitiateCallRequest {
  conversationId: string
  callType: CallType
  mediaType: MediaType
  participantIds?: string[]
}

export interface UpdateMediaStateRequest {
  muted?: boolean
  videoEnabled?: boolean
  screenSharing?: boolean
}

export interface CallStatistics {
  totalCalls: number
  totalDuration: number
  averageDuration: number
  audioCallCount: number
  videoCallCount: number
  missedCallCount: number
  callsByDay: Record<string, number>
}

// RTC API
export const rtcAPI = {
  // 发起通话
  initiateCall: (request: InitiateCallRequest): Promise<Call> => {
    return apiClient.post('/calls/initiate', request)
  },

  // 接受通话
  acceptCall: (callId: string): Promise<Call> => {
    return apiClient.post(`/calls/${callId}/accept`)
  },

  // 拒绝通话
  rejectCall: (callId: string): Promise<Call> => {
    return apiClient.post(`/calls/${callId}/reject`)
  },

  // 结束通话
  endCall: (callId: string): Promise<Call> => {
    return apiClient.post(`/calls/${callId}/end`)
  },

  // 离开通话
  leaveCall: (callId: string): Promise<Call> => {
    return apiClient.post(`/calls/${callId}/leave`)
  },

  // 更新媒体状态
  updateMediaState: (callId: string, request: UpdateMediaStateRequest): Promise<Participant> => {
    return apiClient.put(`/calls/${callId}/media-state`, request)
  },

  // 获取通话详情
  getCall: (callId: string): Promise<Call> => {
    return apiClient.get(`/calls/${callId}`)
  },

  // 获取通话历史
  getCallHistory: (page: number = 0, size: number = 20): Promise<{ calls: Call[], hasMore: boolean, total: number }> => {
    return apiClient.get('/calls/history', {
      params: { page, size }
    })
  },

  // 获取通话统计
  getStatistics: (days: number = 30): Promise<CallStatistics> => {
    return apiClient.get('/calls/statistics', {
      params: { days }
    })
  }
}
